{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "75abd8be",
   "metadata": {},
   "source": [
    "----\n",
    "* 时间：2023/3/16/week04 \n",
    "* 课程：API、机器学习与人工智能   \n",
    "* 学习记录人：林鑫磊  \n",
    "* 学习主题：request\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da9f51f2",
   "metadata": {},
   "source": [
    "# 人脸检测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1097d18d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-03-22T08:55:19.397532Z",
     "start_time": "2023-03-22T08:55:18.745254Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"request_id\":\"1679475317,dfa7cc33-dade-4138-baa2-6d20e84ddf58\",\"time_used\":225,\"faces\":[{\"face_token\":\"c8e5aaee415f9148e963d4d813ede2b0\",\"face_rectangle\":{\"top\":340,\"left\":211,\"width\":260,\"height\":260},\"landmark\":{\"contour_chin\":{\"x\":350,\"y\":591},\"contour_left1\":{\"x\":207,\"y\":398},\"contour_left2\":{\"x\":211,\"y\":426},\"contour_left3\":{\"x\":217,\"y\":453},\"contour_left4\":{\"x\":225,\"y\":480},\"contour_left5\":{\"x\":235,\"y\":506},\"contour_left6\":{\"x\":249,\"y\":530},\"contour_left7\":{\"x\":268,\"y\":552},\"contour_left8\":{\"x\":290,\"y\":571},\"contour_left9\":{\"x\":317,\"y\":586},\"contour_right1\":{\"x\":467,\"y\":387},\"contour_right2\":{\"x\":465,\"y\":414},\"contour_right3\":{\"x\":461,\"y\":441},\"contour_right4\":{\"x\":456,\"y\":467},\"contour_right5\":{\"x\":448,\"y\":493},\"contour_right6\":{\"x\":436,\"y\":518},\"contour_right7\":{\"x\":420,\"y\":540},\"contour_right8\":{\"x\":402,\"y\":561},\"contour_right9\":{\"x\":380,\"y\":580},\"left_eye_bottom\":{\"x\":281,\"y\":405},\"left_eye_center\":{\"x\":283,\"y\":396},\"left_eye_left_corner\":{\"x\":258,\"y\":393},\"left_eye_lower_left_quarter\":{\"x\":268,\"y\":401},\"left_eye_lower_right_quarter\":{\"x\":296,\"y\":404},\"left_eye_pupil\":{\"x\":285,\"y\":394},\"left_eye_right_corner\":{\"x\":309,\"y\":402},\"left_eye_top\":{\"x\":284,\"y\":385},\"left_eye_upper_left_quarter\":{\"x\":269,\"y\":387},\"left_eye_upper_right_quarter\":{\"x\":298,\"y\":390},\"left_eyebrow_left_corner\":{\"x\":233,\"y\":366},\"left_eyebrow_lower_left_quarter\":{\"x\":253,\"y\":367},\"left_eyebrow_lower_middle\":{\"x\":275,\"y\":369},\"left_eyebrow_lower_right_quarter\":{\"x\":296,\"y\":372},\"left_eyebrow_right_corner\":{\"x\":317,\"y\":372},\"left_eyebrow_upper_left_quarter\":{\"x\":253,\"y\":354},\"left_eyebrow_upper_middle\":{\"x\":276,\"y\":354},\"left_eyebrow_upper_right_quarter\":{\"x\":298,\"y\":359},\"mouth_left_corner\":{\"x\":307,\"y\":522},\"mouth_lower_lip_bottom\":{\"x\":350,\"y\":545},\"mouth_lower_lip_left_contour1\":{\"x\":329,\"y\":526},\"mouth_lower_lip_left_contour2\":{\"x\":319,\"y\":533},\"mouth_lower_lip_left_contour3\":{\"x\":332,\"y\":542},\"mouth_lower_lip_right_contour1\":{\"x\":369,\"y\":523},\"mouth_lower_lip_right_contour2\":{\"x\":379,\"y\":530},\"mouth_lower_lip_right_contour3\":{\"x\":367,\"y\":540},\"mouth_lower_lip_top\":{\"x\":349,\"y\":526},\"mouth_right_corner\":{\"x\":388,\"y\":517},\"mouth_upper_lip_bottom\":{\"x\":349,\"y\":524},\"mouth_upper_lip_left_contour1\":{\"x\":338,\"y\":510},\"mouth_upper_lip_left_contour2\":{\"x\":323,\"y\":516},\"mouth_upper_lip_left_contour3\":{\"x\":329,\"y\":524},\"mouth_upper_lip_right_contour1\":{\"x\":359,\"y\":509},\"mouth_upper_lip_right_contour2\":{\"x\":374,\"y\":513},\"mouth_upper_lip_right_contour3\":{\"x\":368,\"y\":521},\"mouth_upper_lip_top\":{\"x\":349,\"y\":512},\"nose_contour_left1\":{\"x\":325,\"y\":402},\"nose_contour_left2\":{\"x\":319,\"y\":457},\"nose_contour_left3\":{\"x\":328,\"y\":485},\"nose_contour_lower_middle\":{\"x\":347,\"y\":491},\"nose_contour_right1\":{\"x\":360,\"y\":400},\"nose_contour_right2\":{\"x\":371,\"y\":454},\"nose_contour_right3\":{\"x\":364,\"y\":483},\"nose_left\":{\"x\":313,\"y\":477},\"nose_right\":{\"x\":378,\"y\":473},\"nose_tip\":{\"x\":346,\"y\":474},\"right_eye_bottom\":{\"x\":402,\"y\":400},\"right_eye_center\":{\"x\":400,\"y\":391},\"right_eye_left_corner\":{\"x\":374,\"y\":400},\"right_eye_lower_left_quarter\":{\"x\":388,\"y\":400},\"right_eye_lower_right_quarter\":{\"x\":415,\"y\":394},\"right_eye_pupil\":{\"x\":396,\"y\":388},\"right_eye_right_corner\":{\"x\":424,\"y\":386},\"right_eye_top\":{\"x\":398,\"y\":379},\"right_eye_upper_left_quarter\":{\"x\":384,\"y\":386},\"right_eye_upper_right_quarter\":{\"x\":413,\"y\":380},\"right_eyebrow_left_corner\":{\"x\":366,\"y\":366},\"right_eyebrow_lower_left_quarter\":{\"x\":387,\"y\":365},\"right_eyebrow_lower_middle\":{\"x\":408,\"y\":361},\"right_eyebrow_lower_right_quarter\":{\"x\":427,\"y\":357},\"right_eyebrow_right_corner\":{\"x\":447,\"y\":356},\"right_eyebrow_upper_left_quarter\":{\"x\":385,\"y\":355},\"right_eyebrow_upper_middle\":{\"x\":405,\"y\":349},\"right_eyebrow_upper_right_quarter\":{\"x\":427,\"y\":347}},\"attributes\":{\"gender\":{\"value\":\"Female\"},\"age\":{\"value\":24},\"smile\":{\"value\":11.781,\"threshold\":50.000},\"headpose\":{\"pitch_angle\":9.228693,\"roll_angle\":-1.6235722,\"yaw_angle\":0.8597287},\"blur\":{\"blurness\":{\"value\":0.607,\"threshold\":50.000},\"motionblur\":{\"value\":0.607,\"threshold\":50.000},\"gaussianblur\":{\"value\":0.607,\"threshold\":50.000}},\"eyestatus\":{\"left_eye_status\":{\"no_glass_eye_open\":99.997,\"no_glass_eye_close\":0.000,\"normal_glass_eye_open\":0.003,\"normal_glass_eye_close\":0.000,\"dark_glasses\":0.000,\"occlusion\":0.000},\"right_eye_status\":{\"no_glass_eye_open\":99.988,\"no_glass_eye_close\":0.000,\"normal_glass_eye_open\":0.012,\"normal_glass_eye_close\":0.000,\"dark_glasses\":0.000,\"occlusion\":0.000}},\"emotion\":{\"anger\":1.331,\"disgust\":0.462,\"fear\":0.254,\"happiness\":1.386,\"neutral\":96.331,\"sadness\":0.164,\"surprise\":0.073},\"facequality\":{\"value\":91.843,\"threshold\":70.100},\"ethnicity\":{\"value\":\"\"},\"beauty\":{\"male_score\":78.105,\"female_score\":80.848},\"mouthstatus\":{\"surgical_mask_or_respirator\":0.000,\"other_occlusion\":0.000,\"close\":99.853,\"open\":0.147},\"eyegaze\":{\"left_eye_gaze\":{\"position_x_coordinate\":0.516,\"position_y_coordinate\":0.371,\"vector_x_component\":0.088,\"vector_y_component\":-0.370,\"vector_z_component\":0.925},\"right_eye_gaze\":{\"position_x_coordinate\":0.439,\"position_y_coordinate\":0.373,\"vector_x_component\":-0.045,\"vector_y_component\":-0.300,\"vector_z_component\":0.953}},\"skinstatus\":{\"health\":68.313,\"stain\":5.324,\"dark_circle\":7.224,\"acne\":5.113},\"glass\":{\"value\":\"None\"}}}],\"image_id\":\"7LXcIlcCuX6sFT2IXEN+/w==\",\"face_num\":1}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "import urllib.request\n",
    "import urllib.error\n",
    "import time\n",
    "\n",
    "http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'\n",
    "key = \"3LRtV97ARNux313_DJkxB5y6SIwgUdYy\"\n",
    "secret = \"WFaYJrG6WLy9tR7vKkkX4NivcIfVsztC\"\n",
    "filepath = r\"lyf.jpeg\"\n",
    "\n",
    "boundary = '----------%s' % hex(int(time.time() * 1000))\n",
    "data = []\n",
    "data.append('--%s' % boundary)\n",
    "data.append('Content-Disposition: form-data; name=\"%s\"\\r\\n' % 'api_key')\n",
    "data.append(key)\n",
    "data.append('--%s' % boundary)\n",
    "data.append('Content-Disposition: form-data; name=\"%s\"\\r\\n' % 'api_secret')\n",
    "data.append(secret)\n",
    "data.append('--%s' % boundary)\n",
    "fr = open(filepath, 'rb')\n",
    "data.append('Content-Disposition: form-data; name=\"%s\"; filename=\" \"' % 'image_file')\n",
    "data.append('Content-Type: %s\\r\\n' % 'application/octet-stream')\n",
    "data.append(fr.read())\n",
    "fr.close()\n",
    "data.append('--%s' % boundary)\n",
    "data.append('Content-Disposition: form-data; name=\"%s\"\\r\\n' % 'return_landmark')\n",
    "data.append('1')\n",
    "data.append('--%s' % boundary)\n",
    "data.append('Content-Disposition: form-data; name=\"%s\"\\r\\n' % 'return_attributes')\n",
    "data.append(\n",
    "    \"gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus\")\n",
    "data.append('--%s--\\r\\n' % boundary)\n",
    "\n",
    "for i, d in enumerate(data):\n",
    "    if isinstance(d, str):\n",
    "        data[i] = d.encode('utf-8')\n",
    "\n",
    "http_body = b'\\r\\n'.join(data)\n",
    "\n",
    "# build http request\n",
    "req = urllib.request.Request(url=http_url, data=http_body)\n",
    "\n",
    "# header\n",
    "req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)\n",
    "\n",
    "try:\n",
    "    # post data to server\n",
    "    resp = urllib.request.urlopen(req, timeout=5)\n",
    "    # get response\n",
    "    qrcont = resp.read()\n",
    "    # if you want to load as json, you should decode first,\n",
    "    # for example: json.loads(qrount.decode('utf-8'))\n",
    "    print(qrcont.decode('utf-8'))\n",
    "except urllib.error.HTTPError as e:\n",
    "    print(e.read().decode('utf-8'))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0734321a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-03-22T09:39:38.323833Z",
     "start_time": "2023-03-22T09:39:38.302027Z"
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (1973090233.py, line 20)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  Input \u001b[1;32mIn [5]\u001b[1;36m\u001b[0m\n\u001b[1;33m    }\u001b[0m\n\u001b[1;37m    ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "Face++人脸识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://api-cn.faceplusplus.com/facepp/v3/detect\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('D:/2022-2023第二学期/API、机器学习与人工智能/api-artificial-intelligence/lyf.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\n",
    "          \"image_base64\":img,\n",
    "          \"api_key \":\"3LRtV97ARNux313_DJkxB5y6SIwgUdYy\",\n",
    "          \"api_secret\":\"WFaYJrG6WLy9tR7vKkkX4NivcIfVsztC\",\n",
    "          'gender,age,smiling,headpose,facequality,emotion,blur,beauty'\n",
    "        }\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data = payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())\n",
    "else:\n",
    "    print(response.status_code)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0145bbc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
